package com.sunther.document.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * set-string转化类
 * @author admin
 */
@MappedTypes(Set.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class SetTypeHandlerString extends BaseTypeHandler<Set> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Set set, JdbcType jdbcType) throws SQLException {
        String param = set.toString().replaceAll("\\[|\\]| ", "");
        preparedStatement.setString(i, param);
    }

    @Override
    public Set getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String sqlSet = resultSet.getString(s);
        return getSet(sqlSet);
    }

    @Override
    public Set getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String sqlSet = resultSet.getString(i);
        return getSet(sqlSet);
    }

    @Override
    public Set getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String sqlSet = callableStatement.getString(i);
        return getSet(sqlSet);
    }

    private Set<String> getSet(String sqlSet) {
        if (StringUtils.isNotBlank(sqlSet)) {
            return Arrays.asList(sqlSet.split(",")).stream()
                    .map(String::toString)
                    .collect(Collectors.toSet());
        }
        return new HashSet();
    }
}
